import { defineComponent, h, nextTick, ref, watch } from 'vue'
import './index.less'
import { UploadType } from './type'
import { Button, message, Upload, type UploadProps } from 'ant-design-vue'
import {
  FileTextOutlined,
  PictureOutlined,
  DownloadOutlined,
} from '@ant-design/icons-vue'
import PropTypes from '@/utils/PropTypes'
import uploadImgApi from '@/api/uploadImg'
import { getFileType } from '@/utils/utils'
import downloadFile from '@/utils/downLoad'
// import uploadApi from '@/api/upload'
export default defineComponent({
  name: 'Upload',
  props: {
    id: PropTypes.string().def(''), // 如果id为空， 就传show
    name: PropTypes.string().def(''),
    item: PropTypes.object<UploadType>(),
    maxCount: PropTypes.number().def(1),
    listType: PropTypes.string().def('picture'),
    uploadData: PropTypes.object().def({ deviceType: '' }),
    fileUrl: PropTypes.any(),
    api: PropTypes.string().def(''),
    validate: PropTypes.func(),
    downLoad: PropTypes.bool().def(false),
  },
  emits: ['update:fileUrl', 'update:icon', 'update:validate'],
  setup(props, { emit }) {
    const isPass = ref<boolean>(true)
    const thumbIcon = ref('picture')
    const isUploading = ref<boolean>(false) // 是否正在上传
    const disabled = ref<boolean>(false)
    const fileList = ref<any>([])
    const echoList = ref<UploadProps['fileList']>([])
    const initImage = () => {
      props.fileUrl.forEach((v: any, index: number) => {
        const i = fileList.value.findIndex((item: any) => item.url == v.url)
        if (i == -1) {
          fileList.value?.push({
            uid: `-${index + 1}`,
            id: v.id,
            name: v.url.split('/')[v.url.split('/').length - 1],
            status: 'done',
            url: process.env.VUE_APP_IMAGE_URL + v.url,
            thumbUrl: process.env.VUE_APP_IMAGE_URL + v.thumbUrl,
          })
        } else {
          fileList.value[i] = v
        }
        echoList.value = [...fileList.value!]
        changeIcon(v.url)
      })
    }
    // 改变上传的icon
    const changeIcon = (val: string) => {
      thumbIcon.value = getFileType(val.split('.')[1])
    }
    // 调用上传接口
    const uoloadFunc = async (file: any) => {
      // 自定义请求的参数和行为
      const formData = new FormData()
      formData.append('file', file)
      formData.append('id', '0')
      try {
        const res: any = await uploadImgApi.upload(formData)
        if (res && res.code == '10000') {
          fileList.value!.length > props.maxCount && fileList.value?.shift()
          fileList.value?.forEach((v: any) => {
            if (file.uid == v.uid) {
              v.status = 'success'
              v.url = res.data.filePath
              v.thumbUrl = res.data.url
              v.id = res.data.fileId
            }
          })
          emit('update:fileUrl', fileList.value)
          emit('update:icon', res.data.path)
          props.validate?.()
          nextTick(() => {
            isUploading.value = false
          })
        }
      } catch (error) {
        console.log(error)
      }
    }
    const handleCustomRequest = (options: any) => {
      let width = null
      let height = null
      isUploading.value = true
      const reader = new FileReader()
      reader.readAsDataURL(options.file)
      reader.onload = async () => {
        const img: HTMLImageElement = document.createElement('img')
        img.src = reader.result as string
        if (/image/.test(options.file.type)) {
          img.onload = async () => {
            width = img.width
            height = img.height
            if (
              (props.item!.height &&
                props.item!.width &&
                width > props.item!.width) ||
              (props.item!.height &&
                props.item!.width &&
                height > props.item!.height!)
            ) {
              isPass.value = false
              fileList.value = []
              return false
            }
            // 自定义请求的参数和行为
            uoloadFunc(options.file)
            isPass.value = true
          }
          thumbIcon.value = 'picture'
        } else {
          uoloadFunc(options.file)
          thumbIcon.value = 'file'
        }
      }
    }
    const handleRemove = (file: any) => {
      const index = fileList.value.findIndex((v: any) => v.uid == file.uid)
      index > -1 && fileList.value.splice(index, 1)
      emit('update:fileUrl', fileList.value)
    }
    const download = async (file: any) => {
      if (!file) return message.error('无文件可下载')
      downloadFile(file).then((res: any) => {
        console.log(res)
      })
    }
    watch(
      () => props.fileUrl.length,
      () => {
        if (props.id && !isUploading.value) initImage()
      },
    )
    watch(
      () => fileList.value!.length,
      () => {
        disabled.value = fileList.value!.length <= props.maxCount ? false : true
      },
    )
    return () => (
      <div>
        <Upload
          v-model:file-list={fileList.value}
          list-type={props.listType}
          class="upload-list-inline"
          maxCount={10}
          multiple
          showUploadList={{
            showDownloadIcon: true,
          }}
          customRequest={handleCustomRequest}
          onRemove={handleRemove}
          onDownload={download}
          v-slots={{
            downloadIcon: () =>
              h(DownloadOutlined, { style: { color: '#2FA4A2' } }),
            iconRender:
              thumbIcon.value == 'picture'
                ? () => h(PictureOutlined, { style: { color: '#2FA4A2' } })
                : () => h(FileTextOutlined, { style: { color: '#2FA4A2' } }),
          }}
        >
          <div class="user-title-box">
            <Button type="primary" class="upload-btn" disabled={disabled.value}>
              点击上传
            </Button>
            <span
              class="user-upload-tips"
              style={{ color: isPass.value ? '#bebebe' : '#ff4d4f' }}
            >
              {props.item?.tips}
            </span>
          </div>
        </Upload>
      </div>
    )
  },
})
